<template>
  <el-card @click="handleDeptList(false)">
    <div class="list-h space">
      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
        size="small"
      >
        <el-form-item label="项目名称" prop="projectNameLike">
          <el-input
            clearable
            class="width-custom140"
            v-model.trim="formInline.projectNameLike"
          />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectCodeLike">
          <el-input
            v-model.trim="formInline.projectCodeLike"
            clearable
            class="width-custom140"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属区域">
          <el-input
            clearable
            v-model.trim="filterText"
            class="width-custom140"
            @clear="clearInput"
            @click.stop="handleDeptList(true)"
          ></el-input>
          <el-tree
            clearable
            ref="treeRef"
            class="filter-tree"
            :data="deptList"
            :props="state.defaultProps"
            :filter-node-method="filterNode"
            v-if="state.showDeptList"
            @node-click="handleChangeDept"
          />
        </el-form-item>

        <el-form-item label="所属单位" prop="projectFactoryNameLike">
          <el-input
            clearable
            class="width-custom140"
            v-model="formInline.projectFactoryNameLike"
          />
        </el-form-item>

        <el-form-item label="项目类型" prop="projectTypeCode">
          <el-select
            v-model="formInline.projectTypeCode"
            value-key="dicCode"
            class="width-custom140"
            clearable
          >
            <el-option
              class="default-option"
              v-for="item in projectTypeList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目年度" prop="projectYear">
          <el-date-picker
            v-model="formInline.projectYear"
            type="year"
            value-format="YYYY"
            placeholder="项目年度"
            class="width-custom140"
            clearable
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="项目管理员" prop="projectLeaderNameLike">
          <el-input
            class="width-custom140"
            v-model="formInline.projectLeaderNameLike"
            clearable
          />
        </el-form-item>

        <el-form-item label="创建时间" prop="timeValue">
          <el-date-picker
            class="width-custom230"
            v-model="timeValue"
            type="daterange"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD"
            @change="handleChangeDate"
            clearable
          />
        </el-form-item>

        <el-form-item class="btn-wrap" style="float: right">
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <span class="exprand-box" @click="pickUp" style="margin-left: 20px">
            <i class="icon snowfont icon-shouqicaidan"></i>
          </span>
        </el-form-item>
      </el-form>
    </div>
    <div class="titleBtn">
      <el-button
        type="primary"
        size="small"
        @click="handlerAdd"
        v-auth="`/projects/manage--add`"
        >创建新项目</el-button
      >
      <el-button
        type="primary"
        size="small"
        @click="exportFunc"
        v-auth="`/projects/manage--export`"
        >导出</el-button
      >
    </div>

    <el-skeleton style="height: 50vh" :rows="8" :loading="loading" animated>
      <el-table
        :data="tableData"
        style="width: 100%"
        height="calc(100vh - 400px)"
        v-loading="loading"
        row-key="id"
        ref="tableRef"
        @selection-change="selectionChange"
        stripe
        :header-cell-style="{
          background: '#F7F9FD',
          color: '#000',
          height: '48px',
          borderTop: '1px soild #E4E8F2'
        }"
      >
        <template #empty>
          <el-empty :image-size="150" description="暂无数据"></el-empty>
        </template>
        <el-table-column
          type="selection"
          :reserve-selection="true"
          width="35"
        />
        <el-table-column type="index" label="序号" width="80" fixed="left">
          <template v-slot="scope">
            <span>{{
              (formInline.pageNum - 1) * formInline.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="projectName"
          label="项目名称"
          width="150"
          fixed="left"
        >
        </el-table-column>
        <el-table-column
          prop="projectCode"
          label="项目编号"
          width="150"
          fixed="left"
        >
        </el-table-column>
        <el-table-column prop="projectRegionName" label="所属区域" width="140">
        </el-table-column>
        <el-table-column
          prop="projectFactoryName"
          label="所属单位"
          width="150"
        ></el-table-column>
        <el-table-column prop="projectTypeName" label="项目类型" width="80">
        </el-table-column>
        <el-table-column prop="projectNatureName" label="项目性质" width="80">
        </el-table-column>
        <el-table-column
          prop="projectNatureName"
          label="项目实施进度"
          width="200"
        >
          <template #default="{ row }">
            <el-select
              v-model="row.projectProgressCode"
              value-key="dicCode"
              class="width-custom180"
              @change="updateRow(row)"
            >
              <el-option
                class="default-option"
                v-for="item in progressList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="declareType" label="申报类型" width="120">
          <template #default="{ row }">
            <span>{{
              row.declareType == 0
                ? "临时申报"
                : row.declareType == 1
                ? "集中申报"
                : "-"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="expensesTypeName"
          label="费用专项类型"
          width="180"
        >
        </el-table-column>
        <el-table-column prop="investmentTypeName" label="投资方向" width="150">
        </el-table-column>
        <el-table-column
          prop="approvalAmount"
          label="项目批准金额(批准后)"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="transferAmount"
          label="调拨资产金额（万元）"
          width="160"
        >
        </el-table-column>
        <el-table-column
          prop="projectLeaderName"
          label="项目管理员"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="projectYear"
          label="项目年度"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="createUserName"
          label="创建人"
          width="80"
        ></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="{ row }">
            <el-button
              type="text"
              v-auth="`/projects/manage--edit`"
              @click="handlerAdd(row)"
              v-show="isShow || userId == row.projectLeaderId"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleOperate(row)"
              >进入</el-button
            >
            <el-button
              class="delete"
              type="text"
              v-auth="`/projects/manage--delete`"
              @click="showDeleteMessageBox(row)"
              v-show="isShow || userId == row.projectLeaderId"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <re-pagination
        v-if="total > 0"
        :total="total"
        v-model:page="formInline.pageNum"
        v-model:limit="formInline.pageSize"
        @pagination="handleChangePage"
      />
    </el-skeleton>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineEmits, watch } from "vue";
import { useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import RePagination from "/@/components/RePagination/index.vue";
import { postDictList } from "/@/api/home";
import {
  getSecDeptTree,
  projectManageList,
  updateProjectDetailApi
} from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import { ElTree } from "element-plus";
import { ElMessageBox } from "element-plus";
import { exportExcel } from "/@/utils/file";
import { judgeRole } from "/@/api/project";

import { postProjectManageDelete } from "/@/api/project";
const formRef = ref<HTMLFormElement | null>(null) as any;
const treeRef = ref<HTMLFormElement | null>(null) as any;
const tableRef = ref();
const emit = defineEmits(["toggleShow"]);
const initData = {
  projectNameLike: "", //项目名称
  projectCodeLike: "",
  createTimeStrStart: "",
  createTimeStrEnd: "",
  projectTypeCode: "", //项目类型
  projectLeaderNameLike: "", //项目负责人
  projectYear: "", //项目年度
  projectRegionCode: "", //区域id
  projectFactoryNameLike: "", //所属单位
  pageNum: 1,
  pageSize: 10
};
const props = defineProps({
  progressList: {
    type: Array,
    default: () => []
  }
});
const localForm = window.sessionStorage.getItem("projectSpaceForm") || "{}";
const formInline = reactive({
  ...initData,
  ...JSON.parse(localForm),
  ...{ pageNum: 1, pageSize: 10 }
});
const timeValue = ref([
  formInline.createTimeStrStart,
  formInline.createTimeStrEnd
]);
const tableData = ref([]);
const total = ref<number>(0);
const router = useRouter();
const loading = ref<boolean>(false);
let projectTypeList = ref([]);
const selectRows = ref<any>([]);
let isShow = ref<boolean>();
let state = reactive({
  defaultProps: {
    children: "children",
    label: "deptDescShrt"
  },
  showDeptList: false
});
const filterNode = (value: string, data) => {
  if (!value) return true;
  return data.deptDescShrt.includes(value);
};
const filterText = ref(window.sessionStorage.getItem("filterText") || "");
const deptList = ref([]);
// watch(filterText, val => {
//   treeRef.value!.filter(val);
// });
let userId = ref("");
if (storageLocal.getItem("info")) {
  userId.value = storageLocal.getItem("info")?.userId;
}

const updateRow = async row => {
  const { data } = await updateProjectDetailApi({
    id: row.id,
    projectProgressCode: row.projectProgressCode,
    projectProgressName: props.progressList.find(
      item => item.dicCode === row.projectProgressCode
    ).dicValue
  });
  if (data) {
    NotifMessage.success("修改成功");
  }
};

//获取数据列表
const getTableList = async () => {
  const { code, data } = await projectManageList({ ...formInline });
  if (code === 200) {
    tableData.value = data.list;
    total.value = data.rows;
  }
};

//改变时间
const handleChangeDate = item => {
  if (item) {
    formInline.createTimeStrStart = item[0];
    formInline.createTimeStrEnd = item[1];
  } else {
    formInline.createTimeStrStart = "";
    formInline.createTimeStrEnd = "";
  }
};

const handleReset = () => {
  formInline.pageNum = 1;
  timeValue.value = null;
  filterText.value = "";
  formInline.projectNameLike = "";
  formInline.projectCodeLike = "";
  formInline.createTimeStrStart = "";
  formInline.createTimeStrEnd = "";
  formInline.projectTypeCode = "";
  formInline.projectLeaderNameLike = "";
  formInline.projectYear = "";
  formInline.projectRegionCode = "";
  formInline.projectFactoryNameLike = "";
  handleChangeDate(null);
  getTableList();
};

const clearInput = () => {
  formInline.projectRegionCode = "";
};

const handleSearch = () => {
  formInline.pageNum = 1;
  getTableList();
};

const handleChangePage = () => {
  getTableList();
};

const handleOperate = row => {
  // ["A", "B"].includes(row.projectTypeCode)
  //   ? router.push(`/projects${row.projectTypeCode}`)
  //   : router.push(`/projectsA`);
  // storageLocal.setItem("projectInfo", {
  //   id: row.id,
  //   name: row.projectName,
  //   projectTypeCode: row.projectTypeCode
  // });
  ["A", "B"].includes(row.projectTypeCode)
    ? router.push(`/projects${row.projectTypeCode}`)
    : row.projectTypeCode == "S"
    ? router.push(`/projectsB/manage/archives`)
    : router.push(`/projectsA`);
  storageLocal.removeItem("sectionInfo");
  storageLocal.setItem("projectInfo", {
    id: row.id,
    name: row.projectName,
    typeCode: row.projectTypeCode,
    typeName: row.projectTypeName,
    leaderId: row.projectLeaderId,
    leaderName: row.projectLeaderName,
    ...row
  });
};

//删除项目
const showDeleteMessageBox = row => {
  ElMessageBox.confirm("确认删除该项目吗？", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    iconClass: "el-icon-warning"
  })
    .then(() => {
      handleDelete(row);
    })
    .catch(() => {});
};

const handleDelete = async row => {
  try {
    const { code, message } = await postProjectManageDelete({ id: row.id });
    if (code === 200) {
      NotifMessage.success(message);
      getTableList();
    } else {
      NotifMessage.error(message);
    }
  } catch (err) {
    console.log(err);
  }
};

//判断是否为超管，1是超管，0不是超管
const deleteJudgeRole = async () => {
  try {
    const { data } = await judgeRole();
    if (data == 1) {
      isShow.value = true;
    } else {
      isShow.value = false;
    }
  } catch (err) {
    console.log(err);
  }
};
deleteJudgeRole();

// 工厂区域
const getDeptTreeFunc = async () => {
  try {
    const { data } = await getSecDeptTree({});
    deptList.value = data || [];
  } catch (err) {
    console.log(err);
  }
};

const handleChangeDept = node => {
  formInline.projectRegionCode = node.id;
  filterText.value = node.deptDescShrt;
  state.showDeptList = false;
};

const handleDeptList = flag => {
  state.showDeptList = flag;
};

// 项目类型
const initProjectTypeList = async () => {
  try {
    const { data } = await postDictList({ dicType: "thd_pro_type" });
    projectTypeList.value = data || [];
  } catch (err) {
    console.log(err);
  }
};

const handlerAdd = (row): void => {
  if (row && row.id) {
    router.push(`/projects/manage/space/add?id=${row.id}`);
  } else {
    router.push(`/projects/manage/space/add`);
  }
};

const pickUp = () => {
  emit("toggleShow");
};

const exportFunc = async () => {
  const arr = selectRows.value.map(val => val.id);
  let formData: any = null;
  if (arr.length === 0) {
    formData = {
      ...formInline,
      pageNum: 1,
      pageSize: 0
    };
  } else {
    formData = {
      ids: arr,
      pageNum: 1,
      pageSize: 0
    };
  }
  exportExcel("/snow-admin/thdProjectManage/export", formData, `项目列表`);
};
const selectionChange = (rows: any) => {
  selectRows.value = rows;
};

watch(formInline, () => {
  window.sessionStorage.setItem("projectSpaceForm", JSON.stringify(formInline));
  window.sessionStorage.setItem("filterText", filterText.value);
});
onMounted(() => {
  getDeptTreeFunc();
  initProjectTypeList();
  getTableList();
});
</script>
<style scoped lang="scss">
:deep .el-dialog__body {
  padding: 20px 40px 8px 10px;
}
.space:deep {
  .el-form-item__label {
    padding: 0 4px 0 0;
  }
  .el-form-item {
    margin-right: 8px;
  }
}
.titleBtn {
  margin-bottom: 20px;
}
.exprand-box {
  display: inline-block;
  width: 32px;
  height: 32px;
  background: rgba(82, 152, 255, 0.1);
  border-radius: 4px;
  line-height: 32px;
  text-align: center;
  cursor: pointer;
  vertical-align: middle;
  i {
    color: #5298ff;
    font-size: 20px;
  }
}
.btn-wrap {
  text-align: right;
  margin-bottom: 12px;
}
.filter-tree:deep {
  &.el-tree {
    position: absolute;
    top: 36px;
    width: 400px;
    max-height: 226px;
    overflow: auto;
    border: 1px solid #e4e8f2;
    z-index: 10;
  }
}

.delete {
  color: #e45d5d;
}
</style>
